package com.hksj.em.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.common.core.model.Rest;
import com.hksj.em.entity.CallOrder;
import com.hksj.em.mapper.CallCaregiverMapper;
import com.hksj.em.query.CallCaregiverQuery;
import com.hksj.em.vo.CallOrderVO;
import com.hksj.em.vo.DevicesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CallCaregiverService extends ServiceImpl<CallCaregiverMapper, CallOrder> {

    @Autowired
    private CallCaregiverMapper callCaregiverMapper;

    public IPage<CallOrderVO> callOrderInfo(CallCaregiverQuery query) {
        // 创建日期格式化工具
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 创建分页对象
        Page<CallOrderVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        List<CallOrder> callOrders = callCaregiverMapper.callOrderInfo(page);
        List<CallOrderVO> voList = callOrders.stream().map(callOrder -> {
            CallOrderVO vo = new CallOrderVO();
            vo.setCode(callOrder.getCode());
            vo.setStatus(callOrder.getStatus());
            vo.setRoomName(callOrder.getRoomName());
            vo.setPlayStatus(callOrder.getPlayStatus());
            vo.setRemark(callOrder.getRemark());
            // Date 转 String
            Date createTime = callOrder.getCreateTime();
            vo.setCreateTime(createTime != null ? sdf.format(createTime) : null);
            return vo;
        }).collect(Collectors.toList());
        page.setRecords(voList);
        return page;
    }

    public Rest<String> updateCallOrderInfo(CallOrder callOrder) {
        // 1. 查询该设备最新的记录
        LambdaQueryWrapper<CallOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CallOrder::getCode, callOrder.getCode()).orderByDesc(CallOrder::getCreateTime).last("LIMIT 1");
        CallOrder latestOrder = callCaregiverMapper.selectOne(queryWrapper);

        if (latestOrder == null) {
            return Rest.fail("未找到该设备的记录");
        }
        // 2. 更新状态为1（完成）
        latestOrder.setStatus(1);
        int updateCount = callCaregiverMapper.updateById(latestOrder);

        if (updateCount > 0) {
            return Rest.ok("状态更新成功");
        } else {
            return Rest.fail("状态更新失败");
        }
    }

    public Rest<String> updatePlayStatus(CallOrder callOrder) {
        LambdaQueryWrapper<CallOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CallOrder::getCode, callOrder.getCode()).orderByDesc(CallOrder::getCreateTime).last("LIMIT 1");
        CallOrder latestOrder = callCaregiverMapper.selectOne(queryWrapper);
        if (latestOrder != null) {
            latestOrder.setPlayStatus(1);
            callCaregiverMapper.updateById(latestOrder);
        }
        return Rest.ok("更新成功");
    }

    @Transactional(rollbackFor = Exception.class)
    public CallOrderVO queryLatestRecord() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LambdaQueryWrapper<CallOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CallOrder::getPlayStatus, 0)
                .orderByDesc(CallOrder::getCreateTime)
                .last("LIMIT 1");
        CallOrder latestOrder = callCaregiverMapper.selectOne(queryWrapper);
        CallOrderVO vo = new CallOrderVO();
        if (latestOrder != null) {
            // 构造 VO
            vo.setCode(latestOrder.getCode());
            vo.setRoomName(latestOrder.getRoomName()); // 确保字段映射正确
            vo.setStatus(latestOrder.getStatus());
            vo.setPlayStatus(latestOrder.getPlayStatus());
            vo.setRemark(latestOrder.getRemark());
            vo.setCreateTime(latestOrder.getCreateTime() != null ? sdf.format(latestOrder.getCreateTime()) : null);

            // 更新状态
            CallOrder updateEntity = new CallOrder();
            updateEntity.setId(latestOrder.getId());
            updateEntity.setPlayStatus(1);
            updateEntity.setUpdateTime(new Date());
            int rows = callCaregiverMapper.updateById(updateEntity);
            if (rows != 1) {
                throw new RuntimeException("更新失败，影响行数: " + rows);
            }
        } else {
            log.warn("未找到 playStatus = 0 的记录");
        }
        return vo;
    }
}
